package com.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * 服务配置
 */
@Configuration
@EnableJpaRepositories(basePackages = "com.**.dao")//扫描repository
@ComponentScan(basePackages = {"com.**.job","com.**.service"}, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class})})
@EnableTransactionManagement
@EnableAspectJAutoProxy
@EnableScheduling
@Conditional(DefaultEnv.class)
public class AppConfig {

    @Autowired
    Environment env;

    private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);

    @Value("#{'${hibernate.properties}'.split(';')}")
    private String[] properties;


    private String scanEntity="com.**.entity";



    //Jpa 事务配置(方法名就是beanID)
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    //Jpa Entity Manager 配置
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource masterDataSource, JpaVendorAdapter jpaVendorAdapter) {
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(masterDataSource);
        emfb.setJpaVendorAdapter(jpaVendorAdapter);
        //设置属性
        Properties jpaProperties = new Properties();
        for(String pro: properties) {
            String[]kv=pro.split(":");
            jpaProperties.put(kv[0], kv[1]);
        }
        emfb.setJpaProperties(jpaProperties);
        emfb.setPackagesToScan(scanEntity);
        return emfb;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter(@Value("${hibernate.dialect}") String dialect) {
        HibernateJpaVendorAdapter hja = new HibernateJpaVendorAdapter();
        hja.setGenerateDdl(false);
        hja.setDatabasePlatform(dialect);
        return hja;
    }







}
